//1. 引入必须的express模块
const express = require("express");
const pool = require("../pool");
//3. 创建路由器
const register = express.Router();

//地址:http://127.0.0.1:3333/register/
register.post("/", (req, res, next) => {
  let uname = req.body.uname;
  let upwd = req.body.upwd;
  let upwd2 = req.body.upwd2;
  var obj = req.body;
  console.log(obj);
  console.log(uname, upwd, upwd2);
  // 查询有无相同的用户名
  const sql = "select * from hbb_user where uname=?";
  pool.query(sql, [uname], (err, results) => {
    if (results.length > 0) {
      res.send({ code: 201, msg: "用户名已被占用" });
      return;
    }
    if (upwd == "") {
      res.send({ code: 202, msg: "密码不能为空" });
      return;
    }
    if (uname == "") {
      res.send({ code: 203, msg: "用户名不能为空" });
      return;
    }
    if (upwd !== upwd2) {
      res.send({ code: 204, msg: "两次密码输入不一致" });
      return;
    }
    if (upwd)
      //执行SQL命令，插入数据
      pool.query(
        "INSERT INTO hbb_user (uname,upwd)VALUES(?,?)",
        [uname, upwd],
        (err, r) => {
          console.log(r);
          res.send({ code: 200, msg: "注册成功" });
        }
      );
  });
});
//将创建好的路由器导出（暴露）
module.exports = register;
